package org.dingxf.config;

import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = { "org.dingxf.dao1" }, sqlSessionFactoryRef = "businessSqlSessionFactory")
public class SqlSessionFactoryCollegeConfig {

    //mapper扫描xml文件的路径
    static final String MAPPER_LOCATION = "org/dingxf/mapper1/*.xml";

    /**
     * 配置数据源
     */
    @Bean(name = "dataSourceBusiness")
    @ConfigurationProperties(prefix = "spring.datasource-business")
    public DataSource dataSourceCollege(){
        return DataSourceBuilder.create().build();
    }

    /**
     * 配置SqlSessionFactory
     */
    @Bean(name = "businessSqlSessionFactory")
    public SqlSessionFactory collegeSqlSessionFactory(@Qualifier("dataSourceBusiness") DataSource dataSource) throws Exception{
        //final SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        final MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSourceCollege());
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCATION));
        return sqlSessionFactoryBean.getObject();
    }

    /**
     * 配置事务管理器
     * @param dataSource
     * @return
     */
    @Bean(name = "businessTransactionManager")
    public DataSourceTransactionManager collegeTransactionManager(@Qualifier("dataSourceBusiness") DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }

    /**
     * 结合类注解MapperScan配置MapperScannerConfigurer
     * @param sqlSessionFactory
     * @return
     * @throws Exception
     */
    @Bean(name = "collegeSqlSessionTemplate")
    public SqlSessionTemplate collegeSqlSessionTemplate(@Qualifier("businessSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}
